package com.family.floor.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.family.common.utils.R;
import com.family.floor.search.config.FloorESConfig;
import com.family.floor.search.feignClient.FloorClient;
import com.family.floor.search.service.FloorSearchService;
import com.family.floor.search.vo.FloorVo;
import com.family.floor.search.vo.SearchParam;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.swing.text.Highlighter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.stream.Collectors;

@Service
public class FloorSearchSericeImpl implements FloorSearchService {
    @Autowired
    private RestHighLevelClient client;
    @Autowired
    private FloorClient floorClient;

    /**
     * 批量上架
     */
    @Override
    public R BatchUp() throws IOException {
        R all = floorClient.findAll();
        List<FloorVo> data = all.getData(new TypeReference<List<FloorVo>>() {
        });
        BulkRequest request = new BulkRequest();
        for (FloorVo floorVo : data) {
            IndexRequest index = new IndexRequest("floor");
            index.id(floorVo.getId()+"");
            String s = JSON.toJSONString(floorVo);
            IndexRequest source = index.source(s, XContentType.JSON);
            request.add(index);
        }
        BulkResponse bulk = client.bulk(request, FloorESConfig.COMMON_OPTIONS);
        if(bulk.hasFailures()){
            return R.error("上架失败");
        }
        List<String> collect = Arrays.stream(bulk.getItems()).map(res -> {
            return res.getId();
        }).collect(Collectors.toList());
        return R.ok().put("data",collect);
    }

    /**
     * 房源检索
     */
    @Override
    public List<FloorVo> search(SearchParam searchParam) throws IOException {
        SearchRequest searchRequest = new SearchRequest("floor");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if(StringUtils.isNotEmpty(searchParam.getParamName())){
            boolQuery.must(QueryBuilders.matchQuery("housingName",searchParam.getParamName()));
        }
        sourceBuilder.query(boolQuery);
        //高亮字段
        if(searchParam.getParamName()!=null){
            HighlightBuilder housingName = new HighlightBuilder().field("housingName");
            housingName.preTags("<b style='color:red'>");
            housingName.postTags("</b>");
            sourceBuilder.highlighter(housingName);
        }
        searchRequest.source(sourceBuilder);
        SearchResponse search = client.search(searchRequest, FloorESConfig.COMMON_OPTIONS);
        SearchHits hits = search.getHits();
        SearchHit[] hits1 = hits.getHits();
        ArrayList<FloorVo> floorVos = new ArrayList<>();
        for (SearchHit hit : hits1) {
            String source = hit.getSourceAsString();
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField housingName = highlightFields.get("housingName");
            Text[] fragments = housingName.fragments();
            FloorVo floorVo = JSONObject.parseObject(source, FloorVo.class);
            floorVo.setHousingName(fragments[0].string());
            floorVos.add(floorVo);
        }

        return floorVos;
    }
}
